package cn.zwxky.android.user.HomePage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.model.Information;
import com.zgscwjm.lsfbbasetemplate.LsfbFragment;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInjectUtils;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SN;
import com.zgscwjm.lsfbbasetemplate.utils.SPUtils;
import com.zgscwjm.lsfbbasetemplate.utils.T;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.zwxky.android.user.R;
import cn.zwxky.android.user.Utils.LittleUtils;
import cn.zwxky.android.user.Utils.NoDoubleClickUtils;
import cn.zwxky.android.user.Utils.Permission;
import cn.zwxky.android.user.Utils.WaveView;


/**
 * Created by Administrator on 2017/3/21 0021.
 */

public class HomePageFragment extends LsfbFragment {

    /**
     * view 对象
     */
    private View view;

    /**
     * activity对象
     */
    private Activity mactivity;

    @ViewInject(R.id.tv_badg)
    private TextView tv_badg;
    private Information info;

    @ViewInject(R.id.wave_view)
    private WaveView mWaveView;

    /**
     * 定位信息
     */
    @ViewInject(R.id.fg_homepage_text_content)
    private TextView text_content;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    private LocationDBHelper dbHelper;


    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what){
                case 1000:
                    text_content.setText("北纬" + LittleUtils.address_weidu + "    东经" + LittleUtils.address_jindu);
                    break;
                case 2000:
                    mWaveView.stop();
                    break;
            }

        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_homepage, null);
        ViewInjectUtils.inject(this, view);

        Permission permission=new Permission(mactivity);
        permission.GetMeshPermission();
        permission.GetAddressBookPermission();
        permission.GetLocationPermission2();
        mLocationClient = new LocationClient(mactivity.getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        initLocation();
        mLocationClient.start();

        //创建StuDBHelper对象
        dbHelper = new LocationDBHelper(mactivity);
        info = new Information();
        getAltitude();
        if (SPUtils.get(mactivity,"fast","0").equals("0")){
            dbHelper.insert("0", "0", "0","");
            SPUtils.put(mactivity,"fast","1");
        }
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        //获取未读消息数并显示
        String unreadNum = SobotApi.getUnreadMsg(mactivity.getApplicationContext()) > 0 ?
                SobotApi.getUnreadMsg(mactivity.getApplicationContext()) + "" : "";
        LsfbLog.e("获取未读消息数并显示"+unreadNum);
        if (unreadNum.isEmpty()){
            tv_badg.setVisibility(View.GONE);
        }else {
            tv_badg.setVisibility(View.VISIBLE);
            tv_badg.setText(unreadNum);
        }
    }

    private SensorManager sensorManager = null;
    private Sensor mPressure;

    public void getAltitude() {
        sensorManager = (SensorManager) mactivity.getSystemService(Context.SENSOR_SERVICE);
        mPressure = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        if (mPressure == null) {
            T.showShort(mactivity, "您的手机不支持气压传感器，无法查看海拔信息");
            return;

        }
//        mPressure = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    SensorEventListener pressureListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub
            float sPV = event.values[0];
            DecimalFormat df = new DecimalFormat("0.00");
            df.getRoundingMode();
            // 计算海拔
            double height = 44330000 * (1 - (Math.pow((Double.parseDouble(df.format(sPV)) / 1013.25),
                    (float) 1.0 / 5255.0)));
            LittleUtils.address_haiba=df.format(height);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub

        }
    };


    /**
     * 用于存储activity对象
     *
     * @param activity
     */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mactivity = activity;
    }

    /**
     * 点击事件
     * @param view
     */
    @OnClick({R.id.fg_home_list,R.id.fg_msg,R.id.fg_homepage_img_dingwei,R.id.fg_homepage_text_save,R.id.big_btn})
    public void onClick(View view){
        switch (view.getId()){
            //已存列表
            case R.id.fg_home_list:
              startActivity(new Intent(mactivity,LocationActivity.class));
                break;
            //消息
            case R.id.fg_msg:
                info.setAppkey("a14627c9117f47da9ab858fc55083aef");
                info.setUid(Config.getUserId());
                info.setUname(LittleUtils.nikename);
                info.setFace(LittleUtils.img_head);
                info.setTel(LittleUtils.phone);
                info.setColor("#374164");
                SobotApi.startSobotChat(mactivity, info);
                break;
            //定位
            case R.id.fg_homepage_img_dingwei:
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    mLocationClient.start();
                    T.showShort(mactivity, "定位中...");
                }
                break;
            //保存
            case R.id.fg_homepage_text_save:
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(curDate);
                    if (LittleUtils.address_jindu.isEmpty() || LittleUtils.address_weidu.isEmpty()) {
                        SN.SnackShow(tv_badg, "没有定位信息可保存");
                        return;
                    }
                   //保存信息
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    dbHelper.insert(LittleUtils.address_jindu, LittleUtils.address_weidu, LittleUtils.address_haiba,str);
                    SN.SnackShow(tv_badg, "定位信息保存成功");
                }

                break;
            case R.id.big_btn:
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    mLocationClient.start();
                    T.showShort(mactivity, "定位中...");
                }
                getAltitude();
                mWaveView.setInitialRadius(250);
                mWaveView.setDuration(2000);
                mWaveView.setStyle(Paint.Style.FILL);
                mWaveView.setColor(Color.parseColor("#525f8c"));
                mWaveView.setInterpolator(new LinearOutSlowInInterpolator());
                mWaveView.start();
                handler.sendEmptyMessageDelayed(2000,2000);
                break;
        }
    }

    @Override
    protected void Resume() {
        sensorManager.registerListener(pressureListener, mPressure,
                SensorManager.SENSOR_DELAY_NORMAL);
        //获取未读消息数并显示
        String unreadNum = SobotApi.getUnreadMsg(mactivity.getApplicationContext()) > 0 ?
                SobotApi.getUnreadMsg(mactivity.getApplicationContext()) + "" : "";
        LsfbLog.e("获取未读消息数并显示"+unreadNum);
        if (unreadNum.isEmpty()){
            tv_badg.setVisibility(View.GONE);
        }else {
            tv_badg.setVisibility(View.VISIBLE);
            tv_badg.setText(unreadNum);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (pressureListener != null) {
            sensorManager.unregisterListener(pressureListener);
        }
    }
    @Override
    public void initData() {

    }

    /**
     * 百度定位设置
     */
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        if (LittleUtils.isNetworkAvailable(mactivity)) {
            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        }else {
            option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
        }
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 1000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);
    }


    /**
     * 定位回调
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            //获取定位结果
            StringBuffer sb = new StringBuffer(256);
            location.getLocType();
            LsfbLog.e("百度错误代码"+location.getLocType());
            double jindu = location.getLongitude();
            double weidu = location.getLatitude();
//            double haiba = location.getAltitude();
            if (location.getLocType() == BDLocation.TypeGpsLocation){

//                if (haiba==4.9E-324){
//                    haiba = location.getAltitude();
//                }

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){

                sb.append("\ndescribe : ");
                sb.append("网络定位成功");

            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {

                // 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");

            } else if (location.getLocType() == BDLocation.TypeServerError) {
//                T.showShort(mactivity,"服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");

            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
//                T.showShort(mactivity,"网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
//                T.showShort(mactivity,"无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
//            if (haiba == 1.01){
//                T.showShort(mactivity,"海拔高度定位失败，请开启手机GPS功能");
//            }
//
//            if (haiba!=4.9E-324){
//                LittleUtils.address_haiba = LittleUtils.DDtoDMS(haiba);
//            }

            if (jindu != 4.9E-324) {
                LittleUtils.address_jindu = LittleUtils.DDtoDMS(jindu);
                LittleUtils.address_weidu = LittleUtils.DDtoDMS(weidu);
                handler.sendEmptyMessage(1000);
                T.showShort(mactivity,"定位成功");
                mLocationClient.stop();
            }
            LsfbLog.e("lalal"+jindu);
            LsfbLog.e("lalal"+weidu);
//            LsfbLog.e("lalal"+haiba);
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

    }

}
